package com.mao.crowd.mvc.controller;

import com.mao.crowd.service.api.MenuService;
import com.mao.crowd.util.ResultEntity;
import entity.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author maomeng
 * @create 2021-06-03- 15:41
 */
//@Controller
@RestController
public class MenuController {

    @Autowired
    private MenuService menuService;

//    @ResponseBody
    @RequestMapping("/menu/get/whole/tree.json")
    public ResultEntity<Menu> getWholeTree(){
//        查询全部的Menu对象
        List<Menu> menuList = menuService.getAll();

//        声明一个根节点menu对象
        Menu root = null;

//        创建一个map对象，用来存储id和menu对象的对应关系
        Map<Integer,Menu> menuMap = new HashMap<>();
//        遍历填充manuMap
        for (Menu menu:menuList){
            Integer id = menu.getId();
            menuMap.put(id,menu);
        }

//        遍历查找根节点，组装父子结点
        for (Menu menu:menuList){
            Integer pid = menu.getPid();
            if (pid == null){
                root = menu;
                continue;
            }
//            如果pid不为null，就根据Pid去menuMap中查找对应的Menu对象
            Menu fatherMenu = menuMap.get(pid);
//            把当前节点对象存入找到的父节点的子节点属性
            fatherMenu.getChildren().add(menu);
        }

//        把根节点对象返回给浏览器
        return ResultEntity.successWithData(root);
    }

//    @ResponseBody
    @RequestMapping("/menu/save.json")
    public ResultEntity<String> saveMenu(Menu menu){

        menuService.saveMenu(menu);

        return ResultEntity.successWithOutData();
    }

//    @ResponseBody
    @RequestMapping("/menu/update.json")
    public ResultEntity<String> updateMenu(Menu menu){
        menuService.updateMenu(menu);
        return ResultEntity.successWithOutData();
    }

//    @ResponseBody
    @RequestMapping("/menu/remove.json")
    public ResultEntity<String> removeMenu(@RequestParam("id") Integer id){
        menuService.removeMenu(id);
        return ResultEntity.successWithOutData();
    }
}
